/**
 * Created by fuxiuyang on 17-5-10.
 * http配置
 */


import axios from 'axios'
import store from '../store/'
import router from '../router/index'
import { LOGOUT } from '../store/mutation-types'

// axios 配置
axios.defaults.timeout = 5000;
// axios.defaults.baseURL = 'http://www.jimikongjian.com:8088';
axios.defaults.baseURL = 'http://localhost:8088';

// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (store.state.token) {
      config.headers.Authentication = store.state.token;
    }
    if (store.state.userInfo.email){
      config.headers.Email = store.state.userInfo.email;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

// http response 拦截器
axios.interceptors.response.use(
  response => {
      return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 401 清除token信息并跳转到登录页面

          store.commit(LOGOUT);
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          })
      }
    }
    // console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
    return Promise.reject(error.response.data)
  });

export default axios;
